import Icon from '@/component/icon'
import Input from '@/component/Input'
import NavBar from '@/component/Nav'
import { baseURL } from '@/utils/request'
import { getTokenInfo } from '@/utils/storage'
import { Toast } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { io } from 'socket.io-client'
import styles from './index.module.scss'

export default function ProfileChat() {
  const [msg, setMsg] = useState('')
  type Message = {
    type?: 'robot' | 'user'
    timestamp?: number
    msg: string
  }
  const [list, setList] = useState<Message[]>([])
  const clientRef = useRef<any>(null)
  const handleSendMsg = () => {
    if (!msg) return Toast.show({ content: '不能输入为空' })
    const userMsg: Message = {
      type: 'user',
      timestamp: Date.now(),
      msg: msg,
    }
    clientRef.current.emit('message', userMsg)
    setList([...list, userMsg])
    setMsg('')
  }
  // 副作用
  useEffect(() => {
    // 建立websoket的客户端实例
    const client = io(baseURL, {
      query: {
        token: getTokenInfo().token,
      },
      transports: ['websocket'],
    })
    clientRef.current = client
    // 连接
    client.on('connect', () => {
      console.log('websocket连接成功+++')
      setList([
        { type: 'robot', timestamp: Date.now(), msg: '亲爱的用户您好，小智同学为您服务' },
        { type: 'user', timestamp: Date.now() + 1, msg: '你好,robot' },
      ])
    })
    client.on('message', (data) => {
      setList((oldlist) => {
        return [...oldlist, { type: 'robot', ...data }]
      })
    })
    return () => {
      client.close()
    }
  }, [])
  useEffect(() => {
    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: 'smooth',
    })
  }, [list])
  // 回车事件handleEnter
  const handleEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSendMsg()
    }
  }
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar>小智同学</NavBar>
      {/* 聊天记录列表 - 开始 */}
      <div className="chat-list">
        {list.map((item) => {
          if (item.type === 'robot') {
            return (
              <div key={item.timestamp} className="chat-item robot">
                <Icon type="iconbtn_xiaozhitongxue" />
                <div className="message">{item.msg}</div>
              </div>
            )
          } else {
            return (
              <div key={item.timestamp} className="chat-item user">
                <img src={'http://toutiao.itheima.net/images/user_head.jpg'} alt="" />
                <div className="message">{item.msg}</div>
              </div>
            )
          }
        })}
      </div>
      {/* 聊天记录列表 - 结束 */}

      {/* 底部消息输入框 */}
      <div className="footer">
        <div className="input-footer">
          <Icon type="iconbianji" />
          <Input
            onKeyUp={(e) => handleEnter(e)}
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
            className="no-border"
            placeholder="请描述您的问题"
          />
          <span onClick={handleSendMsg} className="send">
            发送
          </span>
        </div>
      </div>
    </div>
  )
}
